<?php

namespace services\models;

use Yii;

/**
 * This is the model class for table "iliketry.smash_eggs_game".
 *
 * @property integer $id
 * @property string $title
 * @property string $start_time
 * @property string $end_time
 * @property integer $prize
 * @property string $less_than_gz
 * @property string $more_than_gz
 * @property string $addtime
 * @property string $updatetime
 */
class EggsGame extends \common\models\EggsGame
{

    /*
     * 判断游戏是否开始
     * 游戏已开始:true, 未开始：false
     * */
    public static function is_start(){
        $model = EggsGame::findOne(1);
        $current = date('Y-m-d H:i:s');
        if(empty($model) || $model->start_time > $current || $model->end_time < $current){
            return false;
        }
        return true;
    }


    /*
     * 砸金蛋
     * */
    public function lottery($lkt_uid, $username, $member_score){
        $current = date('Y-m-d H:i:s');
        $ruleInfo = EggsGame::findOne(1)->toArray();
        if(empty($ruleInfo)){
            return ['flag'=> false, 'msg'=>'游戏尚未开始'];//游戏规则未设置
        }

        if($ruleInfo['start_time'] > $current){
            return ['flag'=> false, 'msg'=>'游戏尚未开始'];
        }
        if($ruleInfo['end_time'] < $current){
            return ['flag'=> false, 'msg'=>'游戏已经结束下线'];
        }

        if($member_score < $ruleInfo['prize']){
            $ruleArr = unserialize($ruleInfo['less_than_gz']);
        }
        else{
            $ruleArr = unserialize($ruleInfo['more_than_gz']);
        }

        $n = 0;
        $prizeArr = array();
        foreach($ruleArr as $k => $v){
            $prizeArr[$k][] = $n + 1;
            $n = $n + 100*$v[1];
            $prizeArr[$k][] = $n;
            $prizeArr[$k]['prize'] = $v[0];
        }
        $r = rand(1,10000);
        $result = ['flag' => true, 'msg' => '未中奖', 'prize'=> 0];
        foreach($prizeArr as $value){
            if($r >= $value[0] && $r <= $value[1]){
                $result = $this->win($lkt_uid, $username,$value['prize']);
                break;
            }
        }
        return $result;
    }

    private function win($uid, $username, $prize){
        $insertArr['uid'] = $uid;
        $insertArr['username'] = $username;
        $insertArr['prize'] = $prize;
        $insertArr['addtime'] = date("Y-m-d H:i:s");

        $logModel = new EggsGameLog($insertArr);
        $logModel->save();

        return ['flag' => true, 'msg' => '恭喜你，砸出'.$prize.'试豆', 'prize'=>$prize];
    }
}
